<?php

declare(strict_types=1);
/**
 * This file is part of Hyperf.
 *
 * @link     https://www.hyperf.io
 * @document https://doc.hyperf.io
 * @contact  group@hyperf.io
 * @license  https://github.com/hyperf/hyperf/blob/master/LICENSE
 */
namespace Jooau\Base\Exception\Handler;

use Donjan\Permission\Exceptions\UnauthorizedException;
use Hyperf\ExceptionHandler\ExceptionHandler;
use Hyperf\HttpMessage\Stream\SwooleStream;
use Psr\Http\Message\ResponseInterface;
use Throwable;

class PermissionExceptionHandler extends ExceptionHandler
{
    public function handle(Throwable $throwable, ResponseInterface $response)
    {
        if ($throwable instanceof UnauthorizedException) {
            $this->stopPropagation();

            $body = $throwable->getMessage();

            $code = $throwable->getCode();

            return $response->withStatus($code)
                ->withAddedHeader('content-type', 'application/json')
                ->withBody(new SwooleStream((string)failed($body, [], $code)));
        }

        // 交给下一个异常处理器
        return $response;
    }

    public function isValid(Throwable $throwable): bool
    {
        return $throwable instanceof UnauthorizedException;
    }
}
